package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.NewsMapper;
import edu.sdbi.judge.mapper.NewsTypeMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 新闻列表
 *
 * @author 周涛
 */
@Order(3)
@Service
public class Judge_3 implements GetJudgeIpResultService {

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private NewsTypeMapper newsTypeMapper;

    @Autowired
    private NewsMapper newsMapper;

    private static final Logger logger = LoggerFactory.getLogger(Judge_3.class);

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("3");

        try {
            // 测试基本分页功能
            boolean paginationTestPassed = testPagination(ip);
            if (!paginationTestPassed) {
                studentResult.setScore(0.0);
                studentResult.setResult("分页功能测试失败");
                return studentResult;
            }

            // 测试字段完整性
            boolean fieldTestPassed = testFieldCompleteness(ip);
            if (!fieldTestPassed) {
                studentResult.setScore(0.0);
                studentResult.setResult("字段完整性测试失败");
                return studentResult;
            }

            // 所有测试通过
            studentResult.setScore(4.0);
            studentResult.setResult("分页新闻列表查询功能测试通过");

        } catch (Exception e) {
            logger.error("接口调用异常", e);
            studentResult.setScore(0.0);
            studentResult.setResult("接口调用异常：" + e.getMessage());
        }

        return studentResult;
    }

    // 测试基本分页功能
    private boolean testPagination(String ip) throws Exception {
        // 第一页，每页2条
        String url1 = "http://" + ip + "/news/list?page=1&size=2&newsTypeId=1";
        String result1 = httpUtil.doGet(url1, null, null);
        if (result1 == null) return false;

        JSONObject data1 = JSONObject.parseObject(result1);

        // 检查状态码和消息
        if (data1.getIntValue("code") != 200) {
            return false;
        }

        // 检查返回的数据条数
        int total = data1.getIntValue("total");
        JSONArray rows1 = data1.getJSONArray("rows");

        // 第二页，每页2条
        String url2 = "http://" + ip + "/news/list?page=2&size=2&newsTypeId=2";
        String result2 = httpUtil.doGet(url2, null, null);
        if (result2 == null) return false;

        JSONObject data2 = JSONObject.parseObject(result2);

        // 检查状态码和消息
        if (data2.getIntValue("code") != 200) {
            return false;
        }

        // 检查返回的数据条数
        JSONArray rows2 = data2.getJSONArray("rows");

        // 验证两页数据是否不同
        Set<String> idSet = new HashSet<>();
        for (Object obj : rows1) {
            JSONObject item = (JSONObject) obj;
            idSet.add(item.getString("id"));
        }

        for (Object obj : rows2) {
            JSONObject item = (JSONObject) obj;
            if (idSet.contains(item.getString("id"))) {
                return false;
            }
        }

        return true;
    }

    // 测试字段完整性
    private boolean testFieldCompleteness(String ip) throws Exception {
        String url = "http://" + ip + "/news/list?page=1&size=1&newsTypeId=2";
        String result = httpUtil.doGet(url, null, null);
        if (result == null) return false;

        JSONObject data = JSONObject.parseObject(result);

        // 检查状态码和消息
        if (data.getIntValue("code") != 200) {
            return false;
        }

        // 获取数据列表
        JSONArray rows = data.getJSONArray("rows");

        if (rows == null || rows.isEmpty()) {
            return false;
        }

        // 验证字段完整性
        JSONObject item = rows.getJSONObject(0);

        return item.containsKey("id") &&
                item.containsKey("newsTypeId") &&
                item.containsKey("title") &&
                item.containsKey("createTime");
//        &&
//                item.containsKey("createUsername");
    }

}